package com.bnz.service.impl;

import com.bnz.mapper.ClassesMapper;
import com.bnz.mapper.StudentMapper;
import com.bnz.pojo.Classes;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import com.bnz.util.PageResult;
import com.bnz.vo.StudentVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.mybatis.mapper.example.Example;
import io.mybatis.mapper.example.ExampleWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


@Service
public class StudentServiceImpl implements StudentService {
	@Autowired
	private StudentMapper studentMapper;
	@Autowired
	private ClassesMapper classesMapper;

	//查询查询带分页
	@Override
	public PageResult<Student> search(int page, int pagesize, StudentVo vo) {
		//开始分页
		PageHelper.startPage(page,pagesize);
		//开始条件查询
		ExampleWrapper<Student, Integer> wrapper = studentMapper.wrapper();
		//判断查询条件是否有值
		// if(!StringUtils.isEmpty(vo.getSname())){
		// 	wrapper.like(Student::getSname,"%" + vo.getSname() + "%");
		// }
		// if(!StringUtils.isEmpty(vo.getAddr())){
		// 	wrapper.like(Student::getAddr,"%" + vo.getAddr()  + "%");
		// }
		//因为在前端做了字符串处理，所以，可以直接使用链式语法书写：（平时开发中还是建议使用上面的方法完成）
		wrapper.like(Student::getSname,"%" + vo.getSname() + "%")
			   .like(Student::getAddr,"%" + vo.getAddr()  + "%");

		if(vo.getCid() != 0){
			wrapper.eq(Student::getCid,vo.getCid());
		}
		List<Student> list = wrapper.list();
		for (Student student : list) {
			//得到班级编号
			Optional<Classes> classes = classesMapper.selectByPrimaryKey(student.getCid());
			Classes c = classes.get();   // 必须分开写
			//设置班级名称
			student.setCname(c.getCname());
		}

		//包装成PageInfo
		PageInfo<Student> pageInfo = new PageInfo<>(list);
		//返回分页对象
		return new PageResult<>(pageInfo.getTotal(),pageInfo.getList());
	}

	// 查询所有学生
	@Override
	public List<Student> findAll() {
		return studentMapper.selectByExample(null);
	}

	//3. 添加学生
	@Override
	public void add(Student student) {
		studentMapper.insert(student);
	}

	//4. 修改学生
	@Override
	public void update(Student student) {
		studentMapper.updateByPrimaryKeySelective(student);
	}

	//根据学生编号删除学生
	@Override
	public void delete(List<Integer> sids) {
		System.out.println("sids = " + sids);
		//定义查询实例
		Example<Student> example = new Example<>();
		//定义查询条件
		example.createCriteria().andIn(Student::getId,sids);
		//开始进行查询
		studentMapper.deleteByExample(example);
	}
}
